// Screen.cpp
#include "screen.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include "lvgl/lvgl.h"
#include "squareLine/ui.h"

#include <iostream>

// 私有构造
Screen::Screen() : width_(0), height_(0) {}

// 私有析构
Screen::~Screen() {
    std::cout << "Screen::~Screen()" << std::endl;
}

// 获取唯一实例
Screen& Screen::getInstance() {
    static Screen instance;
    return instance;
}

// 初始化屏幕大小，并分配缓冲区
void Screen::initialize(int width, int height) {
    width_  = width;
    height_ = height;

    lv_init();
    /*Linux frame buffer device init*/
    fbdev_init();

    /*A small buffer for LittlevGL to draw the screen's content*/
    lv_color_t* buf_ = new lv_color_t[width * height];

    /*Initialize a descriptor for the buffer*/
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf_, NULL, width * height);

    /*Initialize and register a display driver*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf = &disp_buf;
    disp_drv.flush_cb = fbdev_flush;
    disp_drv.hor_res  = width;
    disp_drv.ver_res  = height;
    lv_disp_drv_register(&disp_drv);

    /* Linux input device init */
    evdev_init();
    /* Initialize and register a display input driver */
    lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv); /*Basic initialization*/

    indev_drv.type    = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = evdev_read;
    lv_indev_drv_register(&indev_drv);

    ui_init();
}

// 清空缓冲区
void Screen::clear() {}

uint64_t custom_tick_get() {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);

    // 转换为毫秒：秒部分 * 1000 + 纳秒部分 / 1000000
    return (uint64_t)(ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
}
